<?php

namespace App\Services;

use Illuminate\Http\Response;

/**
 * WordPress 权限验证服务
 */
class WordPressAuthService
{
    /**
     * 检查WordPress管理员权限
     *
     * @return Response|null 如果权限检查失败返回Response，成功返回null
     */
    public static function checkAdminAccess(): ?Response
    {
        // 检查是否在WordPress环境中
        if (!function_exists('current_user_can')) {
            return response()->view('errors.wordpress-not-loaded', [], 500);
        }

        // 检查用户是否登录并且是管理员
        if (!is_user_logged_in() || !current_user_can('manage_options')) {
            $loginUrl = function_exists('wp_login_url')
                ? wp_login_url($_SERVER['REQUEST_URI'])
                : '/wp-admin/';

            return response()->view('errors.access-denied', [
                'loginUrl' => $loginUrl
            ], 403);
        }

        return null; // 权限检查通过
    }

    /**
     * 获取当前用户信息
     *
     * @return array|null
     */
    public static function getCurrentUser(): ?array
    {
        if (!function_exists('wp_get_current_user')) {
            return null;
        }

        $user = wp_get_current_user();

        if ($user->ID === 0) {
            return null;
        }

        return [
            'id' => $user->ID,
            'username' => $user->user_login,
            'email' => $user->user_email,
            'display_name' => $user->display_name,
            'roles' => $user->roles,
            'is_admin' => current_user_can('manage_options'),
        ];
    }

    /**
     * 检查用户是否有特定权限
     *
     * @param string $capability
     * @return bool
     */
    public static function userCan(string $capability): bool
    {
        return function_exists('current_user_can') && current_user_can($capability);
    }
}
